package com.etheart.framework.core.fulltextsearch;

import java.io.IOException;
import java.util.List;

import org.apache.lucene.search.highlight.InvalidTokenOffsetsException;
import org.hibernate.search.FullTextQuery;

import com.etheart.framework.core.FrameworkCoreException;
import com.etheart.framework.core.dao.Page;

public class SearchCallback<T> extends AbstractFullTextQueryCallback{

	private int firstResult;
	private int maxResults;
	public SearchCallback(FullTextQueryParameter<T> param){
		super(param);
	}

	protected Object doInHibernate(FullTextQuery query) {
		query.setFirstResult(firstResult);
		query.setMaxResults(maxResults);
		query.setReadOnly(true);
		Page<T> page = new Page<T>();
		int rowCnt = query.getResultSize();
		int pageNum = rowCnt%maxResults==0 ? rowCnt/maxResults : rowCnt/maxResults +1;
		page.setRowCnt(rowCnt);
		List<T> list = query.list();
		page.setObjects(list);
		page.setPageSize(maxResults);
		page.setPageNum(pageNum);
		
		//处理高亮
		if (highlighter != null) {
			try {
				highlighteHandler(list);
			} catch (IllegalArgumentException e) {
				throw new FrameworkCoreException("处理高亮，反射异常", e);
			} catch (IllegalAccessException e) {
				throw new FrameworkCoreException("处理高亮，反射异常", e);
			} catch (IOException e) {
				throw new FrameworkCoreException("处理高亮，IO异常", e);
			} catch (InvalidTokenOffsetsException e) {
				throw new FrameworkCoreException("处理高亮，TokenStream异常", e);
			}
		}
		return page;
	}


	public void setFirstResult(int firstResult) {
		this.firstResult = firstResult;
	}

	public void setMaxResults(int maxResults) {
		this.maxResults = maxResults;
	}


	
	
}
